package com.atguigu.flink.window.keyed;

import com.atguigu.flink.pojo.WaterSensor;
import com.atguigu.flink.util.MyUtil;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2022/11/22
 *
 *
 *    keyBy后，窗口会和key绑定。
 *          countWindow。 相同的key会进入同一个窗口！
 */
public class Demo2_CountWindow
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
            .socketTextStream("hadoop103", 8888)
            .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
            .keyBy(WaterSensor::getId)
            .countWindow(3,3)
            .process(new ProcessWindowFunction<WaterSensor, String, String, GlobalWindow>()
            {
                /*
                     String key: key
                     Context context： 编程环境
                     Iterable<WaterSensor> elements： 窗口中所有的数据
                     Collector<String> out： 输出
                 */
                @Override
                public void process(String key, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {

                        out.collect(MyUtil.parseList(elements).toString());
                }
            }).setParallelism(10)
            .print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }

    }
}
